'use strict';

const { Controller } = require('egg');

/**
 * @Controller 统计接口
 */

class TotalController extends Controller {

    /**
     * @summary 查看重复场次
     * @description 查看重复场次
     * @router post /api/enter/repeat
     * @response 200 baseResponse 成功
     */
    async enterRepeat(){
        const { ctx } = this;
        const payload = ctx.request.body || {};
        let { data } = payload;
        let is_z = data.filter(item=>item.is_z==1)[0];
        let number = data.length
        if(!is_z) return ctx.helper.error({ ctx, msg: '数据不完整' })
        let list = await ctx.model.TotalEnter.findAll({
            where: {
                //找到所有z_amount, number相同的场次
                z_amount: is_z.amount,
                number
            },
            attributes: ['id'],
            include: [
                { 
                    association: ctx.model.TotalEnter.hasMany(ctx.model.TotalEnterDetail, { foreignKey: 'enter_id' }),
                    where: { is_z: 0 } 
                }
            ]
        })
        if(list.length==0)return ctx.helper.success({ ctx, res:{ result: 0 } })
        let other = data.filter(item=>item.is_z==0).map(item=>item.amount).join(',');

        let repeat = []
        list.forEach(item=>{
            let value = item.total_enter_details.map(item=>item.amount).join(',')
            console.log("value:",value)
            console.log("other:",other)
            console.log(value==other)
            if(value==other){
                repeat.push(item.id)
                
            }
        })
        if(repeat.length==0){
            return ctx.helper.success({ ctx, res: { result: 0 } })
        }else{
            return ctx.helper.success({ ctx, res: { result: repeat.join(',') } })
        }
        
    }



    /**
     * @summary 校正旧数据
     * @description 校正旧数据
     * @router get /api/enter/repair
     * @response 200 baseResponse 成功
     */
    async enterRepair(){
        const { ctx } = this;
        let type = 2;
        let error = [];
        for(let i=5818;i<=7545;i++){
            let enter = await ctx.model.TotalEnter.findOne({
                where: { id: i, type }
            })
            if(enter&&type==1){
                let { id, z_value } = enter.dataValues;
                let list = await ctx.model.TotalEnterDetail.findAll({
                    where: { enter_id: id, is_z: 0 }
                })
                let j_win = 0;
                let j_los = 0;
                list.forEach(item=>{
                    if(item.result==1){
                        j_win = j_win + z_value
                    }
                    if(item.result==2){
                        j_los = j_los + item.value
                    }
                })
                let win_num = list.filter(item=>item.result==1).length
                let los_num = list.filter(item=>item.result==2).length
                console.log('修改场次:'+i)
                await enter.update({ win: j_win, los: j_los, win_num, los_num })
                // if(j_win==win&&j_los==los){
                //     console.log(`场次：${i}，数据正确不处理`)
                // }else{
                //     console.log('修正场次:'+i)
                //     await enter.update({ win: j_win, los: j_los })
                // }
            }
            if(enter&&type==2){
                
                let { id, z_value, z_amount } = enter.dataValues;
                console.log('开始执行:'+id)
                let list = await ctx.model.TotalEnterDetail.findAll({
                    where: { enter_id: id, is_z: 0 }
                }); //查询所有非本位的数据
                // list.forEach(item=>{
                    
                //     if(item.value==z_value&&z_value<=2&&item.result!=1)error.push(item.id)

                //     if(item.amount==z_amount&&item.result!=1)error.push(item.id)
                // })

                let j_win = 0;
                let j_low = 0;
                list.forEach(item=>{
                    if(item.result==1){
                        j_win = j_win + z_value
                    }
                    if(item.result==2){
                        j_low = j_low + item.value
                    }
                })
                let win_num = list.filter(item=>item.result==1).length
                let los_num = list.filter(item=>item.result==2).length
                console.log('修改场次:'+i)
                await enter.update({ win: j_win,los: j_low, win_num, los_num })
            }
            
            
        }
        console.log("错误的id:" + error)
        ctx.helper.error({ ctx, msg: error })
    }


    /**
     * @summary 删除场次
     * @description 删除场次
     * @router post /api/enter/delete
     *  @response 200 baseResponse 创建成功
     */
    async enterDelete(){
        const { ctx } = this;
        const payload = ctx.request.body || {};
        let { id } = payload;
        let t = await ctx.model.transaction();
        try{
            await ctx.model.TotalEnter.destroy({
                where:{ id },
                transaction: t
            })
            await ctx.model.TotalEnterDetail.destroy({
                where: {enter_id: id},
                transaction: t
            })
            await t.commit();
            ctx.helper.success({ ctx, res: null })
        }catch(e){
            await t.rollback();
            console.log(e)
            ctx.helper.error({ ctx, msg: '删除失败' })
        }
    }



    /**
     * @summary 统计数据
     * @description 统计列表
     * @router post /api/enter/total
     *  @response 200 baseResponse 创建成功
     */
    async enterTotal(){
        const { ctx } = this;
        const payload = ctx.request.body || {};
        const start_date = payload.start_date;
        const end_date = payload.end_date;
        const start_time = payload.start_time;
        const end_time = payload.end_time;
        const start = payload.start;
        const end = payload.end;
        const z_value = payload.z_value;
        const amount = payload.amount;
        const number = payload.number; //最近多少场次
        const number2_min = payload.number2_min; //最小份数
        const number2_max = payload.number2_max; //最大份数
        const type = payload.type; //类型
        const is_task = payload.is_task
        const names = payload.name;
        const { Op } = ctx.model.Sequelize
        let ids = [];
        if(number){
            let number_search_where = {
                order: [['date', 'DESC'],['time','DESC']],
                limit: number,
                attributes: ['id'],
                where: {}
            }
            if(is_task==1){
                number_search_where.where.task_id = { [Op.not]: null }
            }
            if(is_task==2){
                number_search_where.where.task_id = null 
            }
            if(type){
                number_search_where.where.type = type
            }
            // 搜索近20场的id
            let totalList = await ctx.model.TotalEnter.findAll(number_search_where)
            ids = totalList.map(item=>item.id)
        }
        
        let winAndSearch = [ctx.model.Sequelize.literal(`win_num>los_num`)]
        let losAndSearch = [ctx.model.Sequelize.literal(`win_num<los_num`)]
        let sumAndSearch = [];
        let SearchOr = []; //专门针对名字搜索

        if(number2_min){
            winAndSearch.push({"number": {[Op.gte]: number2_min}})
            losAndSearch.push({"number": {[Op.gte]: number2_min}})
            sumAndSearch.push({"number": {[Op.gte]: number2_min}})
        }
        if(number2_max){
            winAndSearch.push({"number": {[Op.lte]: number2_max}})
            losAndSearch.push({"number": {[Op.lte]: number2_max}})
            sumAndSearch.push({"number": {[Op.lte]: number2_max}})
        }
        
        if(start_date){
            winAndSearch.push({"date": {[Op.gte]: start_date}})
            losAndSearch.push({"date": {[Op.gte]: start_date}})
            sumAndSearch.push({"date": {[Op.gte]: start_date}})
        }

        if(names){
            names.split('|').forEach(item=>{
                SearchOr.push({ 'name': { [Op.like]: '%' + item + '%' } })
            })
        }

        if(end_date){
            winAndSearch.push({"date": {[Op.lte]: end_date}})
            losAndSearch.push({"date": {[Op.lte]: end_date}})
            sumAndSearch.push({"date": {[Op.lte]: end_date}})
        }
        
        if(start_time){
            winAndSearch.push({"time": {[Op.gte]: start_time}})
            losAndSearch.push({"time": {[Op.gte]: start_time}})
            sumAndSearch.push({"time": {[Op.gte]: start_time}})
        }
        if(end_time){
            winAndSearch.push({"time": {[Op.lte]: end_time}})
            losAndSearch.push({"time": {[Op.lte]: end_time}})
            sumAndSearch.push({"time": {[Op.lte]: end_time}})
        }
        if(start){
            winAndSearch.push({"id": {[Op.gte]: start}})
            losAndSearch.push({"id": {[Op.gte]: start}})
            sumAndSearch.push({"id": {[Op.gte]: start}})
        }
        if(end){
            winAndSearch.push({"id": {[Op.lte]: end}})
            losAndSearch.push({"id": {[Op.lte]: end}})
            sumAndSearch.push({"id": {[Op.lte]: end}})
        }
        if(is_task==1){
            winAndSearch.push({"task_id": { [Op.not]: null }})
            losAndSearch.push({"task_id": { [Op.not]: null }})
            sumAndSearch.push({"task_id": { [Op.not]: null }})
        }
        if(is_task==2){
            winAndSearch.push({"task_id": null})
            losAndSearch.push({"task_id": null})
            sumAndSearch.push({"task_id": null})
        }

        let winSearchWhere = {
            [Op.and]: winAndSearch,
            type: 1, //默认1
        }
        
        let losSearchWhere = {
            [Op.and]:losAndSearch,
            type: 1, //默认1
        }
        let sumSearchWhere = {
            [Op.and]:sumAndSearch,
            type: 1, //默认1
        }

        if(SearchOr.length>0){
            sumSearchWhere[Op.or] = SearchOr
        }

    
        if(z_value){
            winSearchWhere.z_value = z_value
            losSearchWhere.z_value = z_value
            sumSearchWhere.z_value = z_value
        }
        if(amount){
            winSearchWhere.amount = amount
            losSearchWhere.amount = amount
            sumSearchWhere.amount = amount
        }
        if(type){
            winSearchWhere.type = type
            losSearchWhere.type = type
            sumSearchWhere.type = type
        }
        if(ids.length>0){
            winSearchWhere.id = ids
            losSearchWhere.id = ids
            sumSearchWhere.id = ids
        }
        let win_enter_number,los_enter_number,sum;
        if(type==3){
            // 胜场
            win_enter_number = await ctx.model.TotalEnter2.count({
                where: winSearchWhere,
            })
            // 负场
            los_enter_number = await ctx.model.TotalEnter2.count({
                where: losSearchWhere,
            })
            // 胜、负数合计
            sum = await ctx.model.TotalEnter2.findAll({
                where: sumSearchWhere,
                attributes: [
                    [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('win')), 'sum_win'],
                    [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('los')), 'sum_los'],
                    [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('win_num')), 'sum_win_num'],
                    [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('los_num')), 'sum_los_num'],
                ],
                raw: true
            })
        }else{
            // 胜场
            win_enter_number = await ctx.model.TotalEnter.count({
                where: winSearchWhere,
            })
            // 负场
            los_enter_number = await ctx.model.TotalEnter.count({
                where: losSearchWhere,
            })
            // 胜、负数合计
            sum = await ctx.model.TotalEnter.findAll({
                where: sumSearchWhere,
                attributes: [
                    [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('win')), 'sum_win'],
                    [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('los')), 'sum_los'],
                    [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('win_num')), 'sum_win_num'],
                    [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('los_num')), 'sum_los_num'],
                ],
                raw: true
            })
        }
        let { sum_win, sum_los, sum_win_num, sum_los_num } = sum[0]

        // 查询符合条件的enter数量， 用来算概率的
        let count = await ctx.model.TotalEnter.count({
            where: {
                ...sumSearchWhere
            }
        })

        // 新增一个逻辑，所有闲家各个数值的次数
        let xjSearch = {
            is_z: 0, //剔除掉本位的
        }
        let include;
        if(type==3){
            include = [
                {
                    association: ctx.model.TotalEnter2Detail.belongsTo(ctx.model.TotalEnter2, { foreignKey: 'enter_id' }),
                    attributes:['id'],
                    where: {
                        [Op.and]:sumAndSearch,
                        type: 1  //默认1
                    }
                }
            ];
            
        }else{
            include = [
                {
                    association: ctx.model.TotalEnterDetail.belongsTo(ctx.model.TotalEnter, { foreignKey: 'enter_id' }),
                    attributes:['id'],
                    where: {
                        [Op.and]:sumAndSearch,
                        type: 1  //默认1
                    }
                }
            ];
        }
        if(SearchOr.length>0){
            include[0].where[Op.or] = SearchOr
        }
        
        if(amount){
            include[0].where.amount = amount
        }
        if(z_value){
            include[0].where.z_value = z_value
        }
        if(type){
            include[0].where.type = type
        }
        if(ids.length>0){
            include[0].where.id = ids
        }

        let amountList, avgInput;
        if(type==3){
            amountList = await ctx.model.TotalEnter2Detail.findAll({
                where: xjSearch,
                include,
                attributes: ['index', 'value']
            })
            avgInput = await ctx.model.TotalEnter2Detail.findAll({
                where: {is_z: 1},
                include,
                attributes: [[ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('input')), 'input_count']],
            })
        }else{
            amountList = await ctx.model.TotalEnterDetail.findAll({
                where: xjSearch,
                include,
                attributes: ['index', 'value']
            })
            avgInput = await ctx.model.TotalEnterDetail.findAll({
                where: {is_z: 1},
                include,
                attributes: [[ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('input')), 'input_count']],
            })
        }
        avgInput = (avgInput[0].dataValues.input_count/count).toFixed(2)

        let avaEnd5List = [];
        //只有三位的时候有这个逻辑
        if(type==2){
            // 现在单独做了一个记录后5位的表格
            // count 就是总数
            for(let i=1;i<=5;i++){
                // 查询符合条件的enter数量， 用来算概率的
                let data = await ctx.model.TotalEnterDetail5.findAll({
                    where: {index:i},
                    include,
                    attributes: [[ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('input')), 'input_count'],[ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('value')), 'value_count']],
                })
                let count = await ctx.model.TotalEnterDetail5.count({
                    where: {
                        index:i,
                        value: {
                            [Op.not]: 0
                        }
                    },
                    include
                })
                let { input_count, value_count } = data[0].dataValues
                let params = {
                    "index": i,
                    "value": (value_count/count).toFixed(2),
                    "value_input": (input_count/count).toFixed(2),
                    "count": count
                }
                avaEnd5List.push(params)
            }
        }


        let num = 10;
        if(type==2||type==3){
            num = 15   
        }
        let xjList = [] 
        for(let i=1; i<=num;i++){
            let number = amountList.filter(item=>item.value==i).length
            if(i!=11)xjList.push({ value: i, number })
        }


        // 本位总数值
        let value_sum = 0;
        //做一个循环，把所有本位数数据查询出来
        let list = []
        for(let i=1;i<=num;i++){
            let bw_count, win, los, bw_sum;
            if(type==3){
                bw_count = await ctx.model.TotalEnter.count({
                    where: {
                        ...sumSearchWhere,
                        z_value: i
                    }
                })
                win = await ctx.model.TotalEnter2.count({
                    where: {
                        ...winSearchWhere,
                        z_value: i
                    }
                })
                los = await ctx.model.TotalEnter2.count({
                    where: {
                        ...losSearchWhere,
                        z_value: i
                    }
                })
                // 胜、负数合计
                bw_sum = await ctx.model.TotalEnter2.findAll({
                    where: {
                        ...sumSearchWhere,
                        z_value: i
                    },
                    attributes: [
                        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('win')), 'bw_win'],
                        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('los')), 'bw_los'],
                        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('win_num')), 'bw_win_num'],
                        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('los_num')), 'bw_los_num'],
                    ],
                    raw: true
                })
            }else{
                bw_count = await ctx.model.TotalEnter.count({
                    where: {
                        ...sumSearchWhere,
                        z_value: i
                    }
                })
                win = await ctx.model.TotalEnter.count({
                    where: {
                        ...winSearchWhere,
                        z_value: i
                    }
                })
                los = await ctx.model.TotalEnter.count({
                    where: {
                        ...losSearchWhere,
                        z_value: i
                    }
                })
                // 胜、负数合计
                bw_sum = await ctx.model.TotalEnter.findAll({
                    where: {
                        ...sumSearchWhere,
                        z_value: i
                    },
                    attributes: [
                        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('win')), 'bw_win'],
                        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('los')), 'bw_los'],
                        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('win_num')), 'bw_win_num'],
                        [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('los_num')), 'bw_los_num'],
                    ],
                    raw: true
                })
            }
            
            value_sum+=bw_count*i;// 数值等于本位的总数*i
            let { bw_win, bw_los, bw_win_num, bw_los_num } = bw_sum[0];
            
            let params = {  
                value:i, //本位值
                bw_count, //该值本位出现的场次
                win, //胜场
                los,  //败场
                bw_win, //胜数
                bw_los, //败数
                bw_win_num, 
                bw_los_num,
                odds: (bw_count/count*100).toFixed(3)
            }
            if(params.value!=11)list.push(params);
            
        }

        let avaList = []
        let normal_sum = 0;
        let normal_input_sum = 0;
        let normal_count = 0;
        let normal_input_count = 0;
        // 筛选非本位的平均数
        for(let i=1;i<=99;i++){
            let avaWhere = {
                index: i,
                is_z: 0,
                value: {
                    [Op.not]: 0  //需要过滤掉020的情况
                }
            }
            let include;
            if(type==3){
                include = [
                        {
                            association: ctx.model.TotalEnter2Detail.belongsTo(ctx.model.TotalEnter2, { foreignKey: 'enter_id' }),
                            where:{
                                number: {
                                    [Op.gt]: i
                                },
                                [Op.and]:sumAndSearch,
                                type: 1
                            } 
                        }
                ];
            }else{
                include = [
                        {
                            association: ctx.model.TotalEnterDetail.belongsTo(ctx.model.TotalEnter, { foreignKey: 'enter_id' }),
                            where:{
                                number: {
                                    [Op.gt]: i
                                },
                                [Op.and]:sumAndSearch,
                                type: 1
                            } 
                        }
                ];
            }
            if(SearchOr.length>0){
                include[0].where[Op.or] = SearchOr
            }
            
            if(ids.length>0){
                include[0].where.id = ids
            }
            if(amount){
                include[0].where.amount = amount
            }
            if(z_value){
                include[0].where.z_value = z_value
            }
            if(type){
                include[0].where.type = type
            }

            let data, count;
            if(type==3){
                data = await ctx.model.TotalEnter2Detail.findAll({
                    where: avaWhere,
                    attributes: [[ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('value')), 'value_count'], [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('input')), 'input_count']],
                    include
                })
                count = await ctx.model.TotalEnter2Detail.count({
                    where: avaWhere,
                    include
                })
            }else{
                data = await ctx.model.TotalEnterDetail.findAll({
                    where: avaWhere,
                    attributes: [[ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('value')), 'value_count'], [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('input')), 'input_count']],
                    include
                })
                count = await ctx.model.TotalEnterDetail.count({
                    where: avaWhere,
                    include
                })
            }
            
            let value = 0;
            let value_input = 0;
            let sum = data[0].dataValues.value_count > 0?data[0].dataValues.value_count:0;
            let sum_input = data[0].dataValues.input_count > 0?data[0].dataValues.input_count:0;
            //累加一下和
            normal_sum+= Number(sum);
            normal_input_sum+= Number(sum_input);
            //累加一下场次
            normal_count+=count;
            normal_input_count+=count;
            if(data[0].dataValues.value_count){
                value = (data[0].dataValues.value_count/count).toFixed(2)
                value_input = (data[0].dataValues.input_count/count).toFixed(2)
            }
            let detail = [];
            let xjnowList = amountList.filter(item=>item.index==i); //所有该位置闲家的数据
            
            for(let i=1; i<=num;i++){
                let number = xjnowList.filter(item=>item.value==i).length
                if(i!=11)detail.push({ value: i, number })
            }
            avaList.push({index: i, value, value_input, detail })
        }

        //本位的平均值
        let avg = (value_sum/count).toFixed(2);
        //闲家的平均值
        let normal_avg = (normal_sum/normal_count).toFixed(2);
        //闲家平均金额
        let normal_avg_input = (normal_input_sum/normal_input_count).toFixed(2);

        ctx.helper.success({ ctx, res:{
            win_enter_number, 
            los_enter_number, 
            sum_win: sum_win==null?0:sum_win, 
            sum_los: sum_los==null?0:sum_los,
            sum_win_num: sum_win_num==null?0:sum_win_num, 
            sum_los_num: sum_los_num==null?0:sum_los_num,
            list,
            avaList,
            avg,
            avgInput, //输入值平均数
            xjList,
            normal_avg,
            normal_avg_input, //闲家平均金额
            avaEnd5List
        }})
    }

    /**
     * @summary 统计列表
     * @description 统计列表
     * @router post /api/enter/getList
     * @response 200 baseResponse 创建成功
     */
    async enterGetList(){
        const { ctx } = this;
        const payload = ctx.request.body || {};
        const page_index = payload.page_index || 0;
        const page_size = payload.page_size;
        const z_value = payload.z_value;
        const amount = payload.amount;
        const number2_min = payload.number2_min; //最小份数
        const number2_max = payload.number2_max; //最大份数
        const start_date = payload.start_date;
        const end_date = payload.end_date;
        const start_time = payload.start_time;
        const end_time = payload.end_time;
        const start = payload.start;
        const end = payload.end;
        const type = payload.type;
        const is_task = payload.is_task
        const { Op } = this.ctx.model.Sequelize
        let AndSearch = [];
        
        if(number2_min){
            AndSearch.push({"number": {[Op.gte]: number2_min}})
        }
        if(number2_max){
            AndSearch.push({"number": {[Op.lte]: number2_max}})
        }
        if(start_date){
            AndSearch.push({"date": {[Op.gte]: start_date}})
        }
        if(end_date){
            AndSearch.push({"date": {[Op.lte]: end_date}})
        }
        if(start_time){
            AndSearch.push({"time": {[Op.gte]: start_time}})
        }
        if(end_time){
            AndSearch.push({"time": {[Op.lte]: end_time}})
        }
        if(start){
            AndSearch.push({"id": {[Op.gte]: start}})
        }
        if(end){
            AndSearch.push({"id": {[Op.lte]: end}})
        }
        if(is_task==1){
            AndSearch.push({ "task_id": { [Op.not]: null } })
        }
        if(is_task==2){
            AndSearch.push({ "task_id": null })
        }
        
        let searchWhere = {
            [Op.and]: AndSearch,
            type: 1  //默认类型就是1
        }
        if(z_value){
            searchWhere.z_value = z_value
        }
        if(amount){
            searchWhere.amount = amount
        }

        if(type){
            searchWhere.type = type
        }
        let total;
        if(type==3){
            total = await ctx.model.TotalEnter2.count({where: searchWhere});
        }else if(type==4){
            total = await ctx.model.TotalEnter3.count({where: searchWhere})
        }else{
            total = await ctx.model.TotalEnter.count({where: searchWhere});
        }
        let res
        if(type==3){
            res = await ctx.model.TotalEnter2.findAndCountAll({
                offset: (page_index - 1) * page_size,
                limit: page_size,
                where: searchWhere,
                order: [['date', 'DESC'],['time', 'DESC']],
                include: [
                    { 
                        association: ctx.model.TotalEnter.hasMany(ctx.model.TotalEnterDetail, { foreignKey: 'enter_id' }),
                        separate: true,
                        order: [['index','ASC']]
                    }
                ]
            })
        }else if(type==4){
            res = await ctx.model.TotalEnter3.findAndCountAll({
                offset: (page_index - 1) * page_size,
                limit: page_size,
                where: searchWhere,
                order: [['date', 'DESC'],['time', 'DESC']],
                include: [
                    { 
                        association: ctx.model.TotalEnter3.hasMany(ctx.model.TotalEnter3Detail, { foreignKey: 'enter_id' }),
                        separate: true,
                        order: [['index','ASC']]
                    }
                ]
            })
        }else{
            res = await ctx.model.TotalEnter.findAndCountAll({
                offset: (page_index - 1) * page_size,
                limit: page_size,
                where: searchWhere,
                order: [['date', 'DESC'],['time', 'DESC']],
                include: [
                    { 
                        association: ctx.model.TotalEnter.hasMany(ctx.model.TotalEnterDetail, { foreignKey: 'enter_id' }),
                        separate: true,
                        order: [['index','ASC']]
                    }
                ]
            })
        }
        

        ctx.helper.success({ ctx, res:{ list: res.rows, total } })
    }


    /**
     * @summary 创建统计
     * @description 创建统计
     * @router post /api/enter/create
     * @response 200 baseResponse 创建成功
     */
    async enterCreate(){
        const { ctx } = this;
        const payload = ctx.request.body || {};
        let t = await ctx.model.transaction();
        try{
            payload.z_value = payload.dataList.filter(item=>item.is_z==1)[0].value
            payload.z_amount = payload.dataList.filter(item=>item.is_z==1)[0].amount
            payload.z_index = payload.dataList.filter(item=>item.is_z==1)[0].index
            let enter = await ctx.model.TotalEnter.create(payload,{
                transaction: t
            })
            let dataList = payload.dataList.map(item=>{
                item.enter_id = enter.id
                if(item.result==""){
                    delete item.result
                }
                return item;
            })
            await ctx.model.TotalEnterDetail.bulkCreate(dataList, {
                transaction: t
            })
            await t.commit();
            ctx.helper.success({ ctx, res: null })
        }catch(e){
            await t.rollback();
            console.log(e)
            ctx.helper.error({ ctx, msg: '添加失败' })
        }
        
        
    }
}

module.exports = TotalController;
